package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.annotation.LogAnno;
import com.example.common.result.Result;
import com.example.controller.base.BaseController;
import com.example.entity.Department;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author daiweiyuan
 * @date 2022/4/5
 */
@RestController
@RequestMapping("/department")
public class DepartmentController extends BaseController {


    @GetMapping("/page") //restful api接口
    @PreAuthorize("hasAuthority('sys:department:find')")
    public Result page(int size, int current, String departmentName) {
        return Result.ok().data(this.departmentService.page(new Page<>(current, size), new QueryWrapper<Department>().likeRight("name",departmentName)));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    public Result list() {
        return Result.ok().data(this.departmentService.list());
    }

    @LogAnno(operateType = "创建部门")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:department:add')")
    public Result add(@RequestBody Department department) {
        departmentService.save(department);
        return Result.created();
    }

    @LogAnno(operateType = "更新部门信息")
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:department:edit')")
    public Result update(@RequestBody Department department) {
        this.departmentService.updateById(department);
        return Result.update();
    }

    @LogAnno(operateType = "查看部门信息")
    @PreAuthorize("hasAuthority('sys:department:edit')")
    @GetMapping("/info")
    public Result info(Integer id) {
        Department department = this.departmentService.getById(id);
        return Result.update().data(department);
    }


    @LogAnno(operateType = "删除部门")
    @PostMapping("/remove")
    @PreAuthorize("hasAuthority('sys:department:del')")
    public Result remove(@RequestBody List<Integer> ids) {
        departmentService.removeByIds(ids);
        ids.forEach(id->{
            Map<String, Object> map = new HashMap<>(2);
            map.put("department_id", id);
            userDepartmentService.removeByMap(map);
        });
        return Result.deleted();
    }


}
